package com.fs.book.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("test")
public class UploadController {

    @PostMapping("upload")
    public String upload(String username, MultipartFile  photo, Model model) throws Exception {
        //保存文件 保存到服务器硬盘
        if(!photo.isEmpty()){ //判断文件是否空
            //MultipartFile的getName() 获取表单的name的值
            //MultipartFile的 getOriginalFilename() 上传文件名
            String filename = photo.getOriginalFilename();
            //后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            String newFileName = System.currentTimeMillis()+suffix;
            String savePath = "D:\\upload";
            //保存  transferTo(File)
            photo.transferTo(new File(savePath,newFileName));

            //保存到Model
            model.addAttribute("photo",newFileName);

            System.out.println(username);
        }



        return "/index";
    }
}
